package dwz.cms.article.util.ftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Logger;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPCommand;
import org.apache.commons.net.ftp.FTPFile;


/** 
* Created by Eclipse
* @author : Yating
* @version:2017年4月18日 上午9:31:24 
* 类说明 
*/
public class FTPUtils {
	private Logger logger = Logger.getLogger(this.getClass().getName());
	private FTPClient ftpClient = new FTPClient();
	private String initPath = "";
	public static final String DELELE = "delete";
	public static final String UPLOAD = "upload";

	/*
	 * path 为ftp默认上传目录
	 */

	public FTPUtils() {
		super();
	}

	public void getConnection(String host, int port, String userName,
			String password) throws IOException {
		try {
			ftpClient.connect(host, port);
			ftpClient.login(userName, password);
			ftpClient.setFileType(FTP.IMAGE_FILE_TYPE);
			logger.info(host + ": login success!");
		} catch (IOException e) {
			logger.info(host + ": not login!");
			e.printStackTrace();
			throw new IOException(host + " ftp链接异常");
		}
	}

	public FTPFile[] getFileList() {// 返回ftp服务器当前目录下所有文件

		FTPFile[] files = null;
		try {
			files = ftpClient.listFiles();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return files;
	}

	public boolean initPath() {// 初始化到上传文件目录
		boolean flag = false;
		try {
			int result = ftpClient.sendCommand(
					FTPCommand.CHANGE_WORKING_DIRECTORY, initPath);
			if (result == 250) {
				flag = true;
			}
			if (result == 450) {
				flag = false;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return flag;
	}

	public void closeConnect() {
		try {
			ftpClient.disconnect();
			logger.info(" disconnect success !!! ");
		} catch (IOException e) {
			logger.info(" not disconnect !!! ");
		}
	}

	public boolean remoteMakeDir(String remotepathName) {// 进入上传目录后，如果文件夹不存在创建目录
		remotepathName = remotepathName.replace("/", File.separator);
		remotepathName = remotepathName.replace("\\", File.separator);
		String[] paths = getSubString(remotepathName);
		boolean flag = false;
		try {
			for (int i = 0; i < paths.length; i++) {
				if (paths[i].trim().equals("")) {
					flag = ftpClient.changeWorkingDirectory(File.separator);
					continue;
				}
				flag = ftpClient.changeWorkingDirectory(paths[i]);
				if (!flag) {
					boolean result = ftpClient.makeDirectory(paths[i]);
					if (!result) {
						logger.info("make dir fail" + paths[i]);
						return result;
					} else {
						flag = ftpClient.changeWorkingDirectory(paths[i]);
						if (!flag) {
							logger.info("cd " + paths[i] + "fail");
							return false;
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return flag;
	}

	public String[] getSubString(String path) {
		String sp = null;
		String[] paths = null;
		if (File.separator.equals("\\")) {
			sp = "\\\\";
		}
		if (File.separator.equals("/")) {
			sp = "\\/";
		}
		paths = path.split(sp);
		return paths;
	}

	public boolean upload(File upLoadFile) throws IOException {
		boolean result = false;
		if (!upLoadFile.isDirectory()) {
			FileInputStream fis = new FileInputStream(upLoadFile);
			String destinationFileName = upLoadFile.getName();
			String tempFileName = "temp_" + destinationFileName;
			// 上传本地文件到服务器上(文件名以'temp_'开头，当上传完毕后，名字改为正式名)
			result = ftpClient.storeFile(tempFileName, fis);
			if (result) {
				// 上传完毕后，名字改为正式名(该方法在远程有效，本地不用此方法，而用renameTo方法)
				result = ftpClient.rename(tempFileName, destinationFileName);

			}
			// 关闭文件流

			fis.close();
		}
		return result;
	}

	public boolean updateload(File updateFile) throws IOException {
		boolean result = false;
		if (!updateFile.isDirectory()) {
			FileInputStream fis = new FileInputStream(updateFile);
			String destinationFileName = updateFile.getName();
			result = ftpClient.storeFile(destinationFileName, fis);
			// 关闭文件流

			fis.close();
		}
		return result;
	}

	public boolean delete(MyFTPFile deleteFile) {
		String fileName = deleteFile.getFile().getName();
		String pathName = deleteFile.getGoalPath()  + fileName;

		boolean flag = initPath();
		if (flag) {
			logger.info(pathName + " initpath success");
		} else {
			logger.info(pathName + " initpath fail");
			return false;
		}
		int result = 0;
		try {
			result = ftpClient.dele(pathName);
		} catch (IOException e) {
			e.printStackTrace();
			logger.info(pathName + " delete fail");
			return false;
		}
		if (result == 250) {
			flag = true;
			logger.info(pathName + " delete success");
		} else {
			flag = false;
			logger.info(pathName + " delete fail");
		}
		return flag;
	}

	public boolean delete(File deleteFile) {
		String pathname = deleteFile.getPath();
		boolean flag = initPath();
		if (flag) {
			logger.info(deleteFile.getPath() + " initpath success");
		} else {
			logger.info(deleteFile.getPath() + " initpath fail");
			return false;
		}
		int result = 0;
		try {
			result = ftpClient.dele(pathname);
		} catch (IOException e) {
			e.printStackTrace();
			logger.info(pathname + " delete fail");
			return false;
		}
		if (result == 250) {
			flag = true;
			logger.info(pathname + " delete success");
		} else {
			flag = false;
			logger.info(pathname + " delete fail");
		}
		return flag;
	}

	public boolean isExist(File file) {
		boolean result = false;
		result = initPath();
		if (result) {
			logger.info(file.getPath() + " initpath success");
		} else {
			logger.info(file.getPath() + " initpath fail");
			return false;
		}
		String name = file.getName();
		String oppositePath = file.getPath();

		String[] paths = getSubString(oppositePath.substring(0, oppositePath
				.length()
				- name.length()));
		try {
			for (int i = 0; i < paths.length; i++) {
				result = ftpClient.changeWorkingDirectory(paths[i]);
				if (!result) {
					break;
				}
			}
			if (result) {
				String[] fileName = ftpClient.listNames();
				if (fileName.length == 0) {
					result = false;
				} else {
					for (int i = 0; i < fileName.length; i++) {
						if (name.equals(fileName[i])) {
							result = true;
							break;
						} else {
							result = false;
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.info(file.getPath() + "not exitst");
			return false;
		}
		if (result) {
			logger.info(file.getPath() + "is exitst");
		} else {
			logger.info(file.getPath() + "not exitst");
		}
		return result;
	}

	public boolean isSameFile(File file) {
		boolean result = false;
		result = initPath();
		if (result) {
			logger.info(file.getPath() + " initpath success");
		} else {
			logger.info(file.getPath() + " initpath fail");
			return false;
		}
		String name = file.getName();
		String oppositePath = file.getPath();
		String[] paths = getSubString(oppositePath.substring(0, oppositePath
				.length()
				- name.length()));
		try {
			for (int i = 0; i < paths.length; i++) {
				result = ftpClient.changeWorkingDirectory(paths[i]);
				if (!result) {
					break;
				}
			}

			if (result) {
				FTPFile[] files = ftpClient.listFiles();
				if (files.length == 0) {
					result = false;
				} else {
					for (int i = 0; i < files.length; i++) {
						if (files[i].getName().equals(file.getName())
								&& files[i].getSize() == file.length()) {
							result = true;
							break;
						} else {
							result = false;
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.info(file.getPath() + " is not same");
		}
		if (result) {
			logger.info(file.getPath() + "is same");
		} else {
			logger.info(file.getPath() + "is not same");
		}
		return result;
	}

	public String isExistFiles(Vector<File> fileVector) {
		boolean result = false;
		String mess = "";
		for (int i = 0; i < fileVector.size(); i++) {
			result = isExist(fileVector.get(i));
			if (result) {
				logger.info(fileVector.get(i).getName() + " is exist");
				mess += fileVector.get(i).getPath() + ",is exist;;;";
			} else {
				mess += fileVector.get(i).getPath() + ",not exist;;;";
			}
		}
		return mess;
	}

	public String isSameFiles(Vector<File> fileVector) {
		boolean result = false;
		String mess = "";
		for (int i = 0; i < fileVector.size(); i++) {
			result = isSameFile(fileVector.get(i));
			if (result) {
				mess += fileVector.get(i).getPath() + ",is same;;;";
			} else {
				mess += fileVector.get(i).getPath() + ",is not same;;;";
			}
		}

		return mess;
	}

	public String deleteFiles(Vector<File> fileVector) {
		boolean result = false;
		String mess = "";
		for (int i = 0; i < fileVector.size(); i++) {
			result = delete(fileVector.get(i));
			if (result) {
				mess += fileVector.get(i).getPath() + ",delete success;;;";
			} else {
				mess += fileVector.get(i).getPath() + ",delete fail;;;";
			}
		}
		return mess;
	}

	public String getPath() {
		String remotepath = null;
		try {
			remotepath = ftpClient.printWorkingDirectory();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return remotepath;
	}

	/*
	 * upLoadFile为文件对象，newPath为在进入初始化ftp后的相对路径
	 */
	public boolean autoUpLoad(File upLoadFile) {
		boolean result = initPath();
		if (result) {
			logger.info(upLoadFile.getPath() + " initpath success");
		} else {
			logger.info(upLoadFile.getPath() + " initpath fail");
			return result;
		}
		String name = upLoadFile.getName();
		String oppositePath = upLoadFile.getPath();
		result = remoteMakeDir(oppositePath.substring(0, oppositePath.length()
				- name.length()));
		if (result) {
			try {
				result = upload(upLoadFile);
			} catch (IOException e) {
				e.printStackTrace();
				logger.info(upLoadFile.getPath() + " upload fail");
				return false;
			}
			if (result) {
				logger.info(upLoadFile.getPath() + " upload success");
			} else {
				logger.info(upLoadFile.getPath() + " upload fail");
			}
		}
		return result;
	}

	public boolean autoUpdate(File updateFile) {
		boolean result = initPath();
		if (result) {
			logger.info(updateFile.getPath() + " initpath success");
		} else {
			logger.info(updateFile.getPath() + " initpath fail");
			return result;
		}
		String name = updateFile.getName();
		String oppositePath = updateFile.getPath();
		result = remoteMakeDir(oppositePath.substring(0, oppositePath.length()
				- name.length()));
		if (result) {
			try {
				result = updateload(updateFile);
			} catch (IOException e) {
				e.printStackTrace();
				logger.info(updateFile.getPath() + " upload fail");
				return false;
			}
			if (result) {
				logger.info(updateFile.getPath() + " upload success");
			} else {
				logger.info(updateFile.getPath() + " upload fail");
			}
		}
		return result;

	}

	public boolean autoUpdate(MyFTPFile updateFile) {

		if (updateFile.getOperation().equals(this.DELELE)) {
			return delete(updateFile);
		}
		boolean result = initPath();
		File file = updateFile.getFile();
		if (result) {
			logger.info(file.getPath() + " initpath success");
		} else {
			logger.info(file.getPath() + " initpath fail");
			return result;
		}
		String name = file.getName();
		String oppositePath = updateFile.getGoalPath();
		result = remoteMakeDir(oppositePath);
		// System.out.println("ftppath: " + oppositePath);
		if (result) {
			try {
				result = updateload(file);
			} catch (IOException e) {
				e.printStackTrace();
				logger.info(file.getPath() + "-->" + updateFile.getGoalPath()
						+ " upload fail");
				return false;
			}
			if (result) {
				logger.info(file.getPath() + "-->" + updateFile.getGoalPath()
						+ " upload success");
			} else {
				logger.info(file.getPath() + "-->" + updateFile.getGoalPath()
						+ " upload fail");
			}
		}
		return result;

	}

	public String autoUpLoad(Vector<File> upLoadFiles) {
		boolean result = false;
		String mess = "";
		for (int i = 0; i < upLoadFiles.size(); i++) {
			result = autoUpLoad(upLoadFiles.get(i));
			if (result) {
				mess += upLoadFiles.get(i).getPath() + ",upload success;;;";
			} else {
				mess += upLoadFiles.get(i).getPath() + ",upload fail;;;";
			}
		}
		return mess;
	}

	public String autoUpdate(Vector<MyFTPFile> updateFiles) {
		boolean result = false;
		String mess = "";
		for (int i = 0; i < updateFiles.size(); i++) {
			result = autoUpdate((MyFTPFile) updateFiles.get(i));
			if (!result)
				mess += updateFiles.get(i).getFile().getPath()+"-->"+updateFiles.get(i).getGoalPath()
						+ ",update fail;;;";
			else
				mess += updateFiles.get(i).getFile().getPath()+"-->"+updateFiles.get(i).getGoalPath()
						+ ",update success;;;";
		}
		return mess;
	}

	// public String autoUpdate(Vector<File> updateFiles) {
	// boolean result = false;
	// String mess = "";
	// for (int i = 0; i < updateFiles.size(); i++) {
	// result = autoUpdate((File) updateFiles.get(i));
	// if (!result) {
	// mess += updateFiles.get(i).getPath() + ",update fail;;;";
	// }
	// mess += updateFiles.get(i).getPath() + ",update success;;;";
	// }
	// return mess;
	// }

	public String autoDelete(Vector<File> deleteFiles) {
		boolean flag = false;
		String mess = "";
		for (int i = 0; i < deleteFiles.size(); i++) {
			flag = delete(deleteFiles.get(i));
			if (flag) {
				mess += deleteFiles.get(i).getPath() + ",delete success;;;";
			} else {
				mess += deleteFiles.get(i).getPath() + ",delete fail;;;";
			}
		}
		return mess;
	}

	public FTPClient getFtpClient() {
		return ftpClient;
	}

	public void setFtpClient(FTPClient ftpClient) {
		this.ftpClient = ftpClient;
	}

	public String getInitPath() {
		return initPath;
	}

	public void setInitPath(String initPath) {
		this.initPath = initPath;
	}

	public FtpError upLoadFilesByThreads(FTPHost[] FTPHosts,
			Vector<MyFTPFile> fileVector) {
		FtpError ftperror = new FtpError();
		ftperror.setMethodName("upload");
		for (int i = 0; i < FTPHosts.length; i++) {
			UpLoadThread upThread = new UpLoadThread(fileVector, FTPHosts[i]
					.getAddress(), FTPHosts[i].getPort(), FTPHosts[i]
					.getUserName(), FTPHosts[i].getPassword(), FTPHosts[i]
					.getInitPath());
			upThread.setFtperror(ftperror);
			upThread.start();
		}
		for (;;) {
			if (ftperror.getHashtable().size() == FTPHosts.length) {
				break;
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return ftperror;
	}

	// public FtpError upLoadFilesByThreads(String[] hostArray, int port,
	// String userName, String password, String initPath,
	// Vector<File> fileVector) {
	// FtpError ftperror = new FtpError();
	// ftperror.setMethodName("upload");
	// for (int i = 0; i < hostArray.length; i++) {
	// UpLoadThread upThread = new UpLoadThread(fileVector, hostArray[i],
	// port, userName, password, initPath);
	// upThread.setFtperror(ftperror);
	// upThread.start();
	// }
	// for (;;) {
	// if (ftperror.getHashtable().size() == hostArray.length) {
	// break;
	// }
	// try {
	// Thread.sleep(2000);
	// } catch (InterruptedException e) {
	// e.printStackTrace();
	// }
	// }
	// return ftperror;
	// }

	public FtpError checkSameByThreads(String[] hostArray, int port,
			String userName, String password, String initPath,
			Vector<File> fileVector) {
		FtpError ftperror = new FtpError();
		ftperror.setMethodName("checksame");
		for (int i = 0; i < hostArray.length; i++) {
			EstimateThread estimateThread = new EstimateThread(fileVector,
					hostArray[i], port, userName, password, initPath);
			estimateThread.setFtperror(ftperror);
			estimateThread.start();
		}
		for (;;) {
			if (ftperror.getHashtable().size() == hostArray.length) {
				break;
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return ftperror;
	}

	public FtpError deleteFilesByThreads(String[] hostArray, int port,
			String userName, String password, String initPath,
			Vector<File> fileVector) {
		FtpError ftperror = new FtpError();
		ftperror.setMethodName("delete");
		for (int i = 0; i < hostArray.length; i++) {
			DeleteThread deleteThread = new DeleteThread(fileVector,
					hostArray[i], port, userName, password, initPath);
			deleteThread.setFtperror(ftperror);
			deleteThread.start();
		}
		for (;;) {
			if (ftperror.getHashtable().size() == hostArray.length) {
				break;
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		return ftperror;
	}

	public static void main(String[] args) throws IOException {
		FTPUtils ftp = new FTPUtils();
		File upLoadFile = new File("D:\\staticPages");
		File[] fileList = upLoadFile.listFiles();

		// File upLoadFile11=new File("test/2.jpg");
		// File upLoadFile22=new File("test/3.jpg");
		// File upLoadFile33=new File("test/4.jpg");
		// File upLoadFile1=new File("test/t1/tt.txt");
		// File upLoadFile2=new File("test/TudouVa1.11_0706A.exe");
		//		
		Vector<File> files = new Vector<File>();
		for (int i = 0; i < fileList.length; i++) {
			if (fileList[i].isFile())
				files.add(fileList[i]);
		}
		// files.add(upLoadFile);
		// files.add(upLoadFile1);
		// files.add(upLoadFile2);
		// files.add(upLoadFile11);
		// files.add(upLoadFile22);
		// files.add(upLoadFile33);
		// String[] hostArray={"192.168.100.1","192.168.100.3"};
		// FtpError ftperror=ftp.deleteFilesByThreads(hostArray, 21, "teldev",
		// "8753EDU!", "/home/teldev", files);
		String[] hostArray = { "202.102.123.239" };
		// FtpError ftperror = ftp.upLoadFilesByThreads(hostArray, 21, "city",
		// "city", "/", files);
		// System.out.println(hostArray[0] + ":" + ftperror.getMethodName()
		// + ":::" + ftperror.getHashtable().get(hostArray[0]));
		// //
		// System.out.println(hostArray[1]+":"+ftperror.getMethodName()+":::"+ftperror.getHashtable().get(hostArray[1]));
		// System.out.println("end");
	}
}
 